import sys
import unittest
from test import test_support
from nirvanix import Nirvanix
from nirvanix import Session
import nirvanixutils

from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
import wsgiref.handlers

"""
To run the Unit Tests change the values below with the real values from your account. This
is required to run the unit tests.  You can get this information at http://nmp.nirvanix.com
"""
appKey = "YOURAPPKEY"
masterUsername = "YOURMASTERACCTNAME"
masterPassword = "YOURMASTERACCTPASSWORD"
childUsername = "YOURCHILDACCTNAME"
childPassword = "YOURCHILDACCTPASSWORD"

class AuthenticationTests(unittest.TestCase):

    # Define setUp and tearDown only if needed
    def test_login(self):
        session = Session(appKey, masterUsername, masterPassword)
        assert(session.sessionToken)

    def test_login_failed(self):
        try:
            session = Session(appKey, masterUsername, "x")
        except nirvanixutils.NirvanixException, e:
            if e.message != 'Login Failed':
                raise e
            # Expected exception; passed test
        else:
            raise

    def test_logout(self):
        session = Session(appKey, masterUsername, masterPassword)
        del session

class IMFSTests(unittest.TestCase):

    # call list folder and verify at least one sub folder exists.
    # TEST SETUP: This test expects one or more folders to exist in the root of your account.
    def test_listfolder(self):
        session = Session(appKey, masterUsername, masterPassword)
        # get the imfs object.
        imfs = Nirvanix('IMFS', session);
        # setup the listfolder options.
        options = {'folderPath':'/','pageNumber':'1','pageSize':'500'}
        doc = imfs.ListFolder(options,False)
        # get the foldercount from the resulting xml.
        folderCount = doc.getElementsByTagName("TotalFolderCount")[0].childNodes[0].data
        # validate there is at least one folder.
        assert(int(folderCount) > 0)

class SharingTests(unittest.TestCase):

    # call createhosteditem and verify the download link is returned (could expand to verify file contents).
    # TEST SETUP: This test expect a file /sharetest/sharetest.txt to exist in your account.
    def test_createhosteditem(self):
        session = Session(appKey, masterUsername, masterPassword)
        
        # Create a sharing object.
        sharing = Nirvanix('Sharing', session);
        # setup the options including the share path.
        options = {'sharePath':'/sharetest/sharetest.txt'}
        doc = sharing.CreateHostedItem(options,False)
        
        # get the download link to verify the result was returned properly.
        downloadLink = doc.getElementsByTagName("DownloadLink")[0].childNodes[0].data
        # validate the download link returned something.
        assert(downloadLink != '')
        
        # Remove the share for the next test.
        sharing.RemoveHostedItem(options, False)

class MetadataTests(unittest.TestCase):

    # call getmetadata to verify the metadata on a file.
    # TEST SETUP: This test expects /metadatatest/metadatatest.txt to exist in your account.
    def test_getmetadata(self):
        # login with a session.
        session = Session(appKey, masterUsername, masterPassword)
        # Create the metadata object.
        metadata = Nirvanix('Metadata', session);
        # set some data first
        options = {'path':'/metadatatest/metadatatest.txt', 'metadata':'datatest:testvalue'}
        doc = metadata.setMetadata(options,False)
        # set the options and get the metadata for the file.
        options = {'path':'/metadatatest/metadatatest.txt'}
        doc = metadata.getMetadata(options,False)
        # get the value from the node.
        data = doc.getElementsByTagName("Type")[0].childNodes[0].data
        assert(data == 'datatest')
        
class TestResults(webapp.RequestHandler):
    def get(self):
        # we need to do this because the tests don't wait to write the results to the response.
        print ('Content-Type: text/plain')
        print ('')
        suite = unittest.TestSuite()
        suite.addTest(unittest.makeSuite(AuthenticationTests))
        suite.addTest(unittest.makeSuite(IMFSTests))
        suite.addTest(unittest.makeSuite(SharingTests))
        suite.addTest(unittest.makeSuite(MetadataTests))
        test_support.run_suite(suite)

        
def test_main():
    application = webapp.WSGIApplication([('/test/', TestResults)],debug=True)
    wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
    test_main()

